<template>
  <div class="app-container">

    <!-- 表头 查询与新增 -->
    <el-row>
      <el-col :span="24">
        <div class="filter-container">
          <el-input v-model="listQuery.query" placeholder="图片名称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter"/>
          <el-select
            v-model="listQuery.imageStatus"
            placeholder="图片状态"
            clearable
            class="filter-item"
            style="width: 150px"
            @change="handleFilter">
            <el-option v-for="(value, key) in statusOptions" :key="key" :label="value" :value="key"/>
          </el-select>
          <el-select
            v-model="listQuery.imageType"
            placeholder="图片类型"
            clearable
            class="filter-item"
            style="width: 150px"
            @change="handleFilter">
            <el-option v-for="(value, key) in typeOptions" :key="key" :label="value" :value="key"/>
          </el-select>
          <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
          <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-circle-plus-outline" @click="uploadOrderImage">图片上传</el-button>
        </div>
      </el-col>
    </el-row>

    <!-- 表格list -->
    <el-row>
      <el-col :span="24" :gutter="24">
        <el-table
          v-loading="listLoading"
          :key="tableKey"
          :data="list"
          :height="tableHeight"
          element-loading-text="Loading"
          border
          fit
          style="width: 100%;"
          highlight-current-row>
          <el-table-column align="center" label="序号" width="80">
            <template slot-scope="scope">
              {{ scope.$index }}
            </template>
          </el-table-column>
          <!--<el-table-column show-overflow-tooltip label="订单图片ID" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
                {{ scope.row.orderImgId }}
            </template>
          </el-table-column>-->
          <el-table-column show-overflow-tooltip label="订单ID" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.orderId }}
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip label="图片名称" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.imgName }}
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip label="图片类型" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.imageType | typeFilter }}
            </template>
          </el-table-column>

          <el-table-column show-overflow-tooltip label="订单图片" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              <!--{{ scope.row.orderImg }}-->
              <img v-if="scope.row.orderImg" :src="scope.row.orderImg" style="width: 50px;height: 50px;">
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip label="图片状态" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.imageStatus | validFilter }}
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip class-name="status-col" label="创建时间" style="width: 10%" align="center">
            <template slot-scope="scope">
              <i class="el-icon-time"/>
              <span>{{ scope.row.createdTime | timeFilter }}</span>
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip label="操作人" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.operatorCode }}
            </template>
          </el-table-column>
          <!--<el-table-column show-overflow-tooltip class-name="status-col" label="修改时间" style="width: 10%" align="center">
			 <template slot-scope="scope">
              <i class="el-icon-time"/>
              <span>{{ scope.row.modifiedTime | timeFilter}}</span>
            </template>
          </el-table-column>-->

          <el-table-column label="操作" align="center" width="300" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" @click="handleUpdate(scope.row)">
                图片编辑
              </el-button>
              <el-button size="mini" type="primary" @click="downPhoto(scope.row)">
                图片下载
              </el-button>
               <el-button size="mini" type="danger" @click="handleDelete(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>

    <!-- 分页控件 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.pageNum"
      :limit.sync="listQuery.pageSize"
      layout="total, sizes, prev, pager, next"
      style="float:right;"
      @pagination="fetchData"/>

    <!-- 编辑弹窗 -->
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      width="60%">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="right"
        label-width="100px"
        style="width: 100%;">

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="订单图片ID" label-width="105px" prop="orderImgId">
              <el-input v-model="temp.orderImgId" :disabled="dialogStatus === 'update'"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="订单ID" label-width="105px" prop="orderId">
              <el-input :disabled="dialogStatus === 'update'" v-model="temp.orderId"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="图片名称" label-width="105px" prop="imgName">
              <el-input v-model="temp.imgName"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="图片类型" label-width="105px" prop="imageType">
              <!--<el-input v-model="temp.imageType"/>-->
              <el-select v-model="temp.imageType" filterable clearable placeholder="图片状态">
                <el-option
                  v-for="(value, key) in typeOptions"
                  :key="key"
                  :label="value"
                  :value="key"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="图片状态" label-width="105px" prop="imageStatus">
              <el-select v-model="temp.imageStatus" filterable clearable placeholder="图片状态">
                <el-option
                  v-for="(value, key) in statusOptions"
                  :key="key"
                  :label="value"
                  :value="key"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="操作人" label-width="105px" prop="operatorCode">
              <el-input v-model="temp.operatorCode"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="订单图片" label-width="105px" prop="orderImg">
              <!--<el-input v-model="temp.orderImg"/>-->
              <!--<img v-if="temp.orderImg" :src="temp.orderImg" class="avatar">-->
              <el-upload
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :action="uploadUrl"
                class="avatar-uploader">
                <img v-if="temp.orderImg" :src="temp.orderImg" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"/>
              </el-upload>

            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">确认</el-button>
        <el-button @click="dialogFormVisible = false">取消</el-button>
      </div>
    </el-dialog>

    <!-- 编辑弹窗 -->
    <el-dialog
      title="订单图片上传"
      :visible.sync="dialogImageVisible"
      width="70%">
      <el-form
        ref="dataForm"
        :rules="rulesPhoto"
        :model="orderImage"
        label-position="right"
        label-width="100px"
        style="">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="订单号"  label-width="120px" prop="maxNum">
              <el-input v-model="orderImage.orderId" disabled/>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="图片类型" label-width="120px" prop="minNum">
              <el-select v-model="orderImage.imageType"  class="filter-item" placeholder="请选择图片类别">
                <el-option v-for="item in photoOptions"
                           :key="item.value"
                           :label="item.label"
                           :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="" label-width="120px" prop="minNum">
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="注意事项" label-width="120px" prop="minNum">
              <el-tag type="warning" style="font-size:18px">必须同时上传两个版本，前台才可下载图片！</el-tag>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="订单图片" label-width="120px" prop="orderImg">
              <el-upload
                class="upload-demo"
                drag
                :on-success="handleAvatarSuccess1"
                :before-upload="beforeAvatarUpload1"
                :on-remove="handleRemove"
                :action="uploadUrl"
                :file-list="fileList"
                list-type="picture"
                multiple>
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过100MB</div>
              </el-upload>
              <!--<tinymce ref="uploadModel" :custom-modal="editModal" :upload-url="uploadUrl" :height="300" v-model="orderImage.orderImg"/>-->
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitUpload">确认</el-button>
        <el-button @click="dialogImageVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import SxOrderImgApi from '@/api/manage/SxOrderImgApi'
import SxOrderRecordApi from '@/api/manage/SxOrderRecordApi';
import waves from '@/directive/waves' // Waves directive
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
export default {
  directives: { waves },
  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        1: 'success',
        2: 'gray',
        0: 'danger'
      }
      return statusMap[status]
    },
    validFilter(status) {
      const statusMap = {
        1: '新传',
        2: '修图',
        3: '无效'
      }
      return statusMap[status]
    },
    typeFilter(status) {
      const statusMap = {
        1: '原图版',
        2: '分享版'
      }
      return statusMap[status]
    },
    timeFilter(time) {
      if (time) {
        return new Date(time).Format('yyyy-MM-dd hh:mm:ss')
      } else {
        return ''
      }
    }
  },
  data() {
    return {
	    tableKey: 0, // 表格key值
      list: null, // 表格对象
      listLoading: true, // 表格加载框
	    	total: 0, // 分页总数
		    tableHeight: window.innerHeight - 220, // 表格高度
      listQuery: { // 表格查询对象
        pageNum: 1,
        pageSize: 10,
        query: '',
        imageStatus: '',
        imageType: '',
        orderId: '',
        orderImgId: ''
      },
      temp: {}, // 编辑框临时变量
      statusOptions: { // 有效无效下拉框
        '1': '新传',
        '2': '修图',
        '3': '无效'
      },
      photoOptions: [ //图片类型下拉框
        {label: '原图版',
          value: '1' },
        {label: '分享版',
          value: '2'
        }],
      typeOptions: { // 高清普通下拉框
        '1': '原图版',
        '2': '分享版'
      },
      fileList: [
        /*{
          name: '',
          url: ''
        }*/
      ],//上传订单照片数组
      dialogFormVisible: false, // 编辑框显示
      dialogImageVisible: false, //图片上传显示
      dialogStatus: '', // 编辑框更新插入状态
      textMap: { // 编辑框标题
        update: '编辑',
        create: '创建'
      },
      uploadUrl: process.env.BASE_API + '/file/upload',
      rules: { // 编辑框校验规则
		   orderImgId: [{ required: true, message: '请输入订单图片ID', trigger: 'change' }],
		   orderId: [{ required: true, message: '请输入订单ID', trigger: 'change' }],
		   orderImg: [{ required: true, message: '请输入订单图片', trigger: 'change' }],
		   imageStatus: [{ required: true, message: '请输入图片状态', trigger: 'change' }],
        //		   operatorCode: [{required: true, message: '请输入操作人', trigger: 'change'}],
		   imgName: [{ required: true, message: '请输入图片名称', trigger: 'change' }],
		   imageType: [{ required: true, message: '请输入图片类型', trigger: 'change' }]
      },
      orderImage: {
        'orderId' :'',
        'details' : '',
        'imageType': '1'
      }, //上传框临时变量
      rulesPhoto: { //图片编辑框校验规则
        imageType: [{required: true, message: '请选择图片类型', trigger: 'change'}],
      }
    }
  },
  computed: {
    validSwitch: {
      // getter
      get: function() {
        return this.temp.validFlag === '1'
      },
      // setter
      set: function(newValue) {
        if (newValue) {
          this.temp.validFlag = '1'
        } else {
          this.temp.validFlag = '0'
        }
      }
    }
  },
  created() {
    const orderId = this.$route.params && this.$route.params.orderId
    this.listQuery.orderId = orderId
    /* this.product = this.$route.params*/

    this.fetchData()
  },
  methods: {

    /**
     * 打开上传图片弹窗
     */
    uploadOrderImage () {
      debugger
      let that = this;
      that.fileList = [];
      this.imgDetailArr = [];
      this.orderImage.orderId = this.listQuery.orderId
      this.dialogImageVisible = true

    },

    /**
     * 上传订单图片
     */
    submitUpload() {
      debugger
      let that = this;
      this.$set(this.orderImage , 'details' ,JSON.stringify(this.imgDetailArr));
      this.$set(this.orderImage , 'operatorCode' , localStorage.getItem("token"));
      SxOrderRecordApi.orderImgCreate(this.orderImage).then((res) => {
        this.dialogImageVisible = false;
        this.$message({
          title: '成功',
          message: '上传订单图片成功',
          type: 'success',
          duration: 1000,
          onClose() {
            that.fetchData();
          }
        })

      })
    },

    /**
     * 上传订单图片成功
     */
    handleAvatarSuccess1(res, file, fileList) {
      debugger
      let that = this;
      if (file) {
        let tempObj = {};
        that.$set(tempObj, 'orderImg', res.data[0]);
        that.$set(tempObj, 'imgName', file.name);
        that.$set(tempObj, 'uid', file.uid);
        this.imgDetailArr.push(tempObj);
      }
    },

    handleRemove(file, fileList) {
      let imageDetailArr = [];
      let that = this;
      this.$_.forEach(fileList ,(v , k) => {
        let tempObj = {};
        that.$set(tempObj, 'orderImg', v.response.data[0]);
        that.$set(tempObj, 'imgName', v.name);
        that.$set(tempObj, 'uid', v.uid);
        imageDetailArr.push(tempObj);
      });
      this.imgDetailArr = imageDetailArr;
    },

    /**
     * 上传订单图片
     */
    beforeAvatarUpload1(file) {
      debugger
      const isLt2M = file.size / 1024 / 1024 < 100
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 100MB!')
      }
      return isLt2M
    },

    handleAvatarSuccess(res, file) {
      this.temp.orderImg = res.data[0]
    },

    /**
       * 图片下载
       */
    downPhoto(row) {

      // 必须同源才能下载
      /* var alink = document.createElement("a");
        alink.href = row.orderImg;
        alink.download = row.imgName; //图片名
        alink.click();*/
      // window.location.href = row.orderImg;

      this.downloadIamge(row.orderImg, row.imgName)
    },
    downloadIamge(imgsrc, name) { // 下载图片地址和图片名
      let _sel = this;
      var image = new Image();
      // 解决跨域 Canvas 污染问题
      image.setAttribute("crossOrigin", "anonymous");
      if (imgsrc.indexOf('?') !== -1) {
        imgsrc += '&r=' + Math.random()
      } else {
        imgsrc += '?r=' + Math.random()
      }

      image.onload = function() {
        var canvas = document.createElement("canvas");
        canvas.width = image.width;
        canvas.height = image.height;
        var context = canvas.getContext("2d");
        context.drawImage(image, 0, 0, image.width, image.height);

        //得到图片的base64编码数据  "image/png"
        var url = canvas.toDataURL({format: 'png', multiplier: 4});
        // var strDataURI = url.substr(22, url.length);
        var blob = _sel.dataURLtoBlob(url);
        var objurl = URL.createObjectURL(blob);

        var a = document.createElement("a"); // 生成一个a元素
        var event = new MouseEvent("click"); // 创建一个单击事件
        a.download = name || "photo"; // 设置图片名称
        a.href = objurl; // 将生成的URL设置为a.href属性
        a.dispatchEvent(event); // 触发a的单击事件
      };
      image.src = imgsrc;
    },

    /**
     * 图片过大转换
     */
    dataURLtoBlob(dataurl) {
      var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
      while(n--){
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], {type:mime});
    },

    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 50
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 50MB!')
      }
      return isLt2M
    },

	  /**
       * 获取表格数据
       */
    fetchData() {
      const that = this
      this.listLoading = true
      this.$http.all([SxOrderImgApi.getPage(this.listQuery)])
        .then(this.$http.spread(function(perms) {
          that.list = perms.rows
          that.total = perms.total
          that.listLoading = false
        }))
    },
    /**
       * 新增弹窗
       */
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    /**
       * 清空弹窗内容
       */
    resetTemp() {
      this.temp = {
        orderImgId: '',
        orderId: '',
        orderImg: '',
        imageStatus: '',
        createdTime: '',
        operatorCode: '',
        modifiedTime: '',
        imgName: '',
        imageType: '',
        validFlag: '1'
      }
    },
    /**
       * 确定新增
       */
    createData() {
      const that = this
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          SxOrderImgApi.insert(this.temp).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 1000,
              onClose() {
                that.fetchData()
              }
            })
          })
        }
      })
    },
    /**
       * 编辑弹窗
       */
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    /**
       * 确认编辑
       */
    updateData() {
      const that = this
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          SxOrderImgApi.update(tempData).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 1000,
              onClose() {
                that.fetchData()
              }
            })
          })
        }
      })
    },
    /**
       * 删除操作
       */
    handleDelete(row) {
      const that = this
      SxOrderImgApi.remove({ orderImgId: row.orderImgId }).then(() => {
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 1000,
          onClose() {
            that.fetchData()
          }
        })
      })
    },
    /**
       * 搜索过滤
       */
    handleFilter() {
      this.listQuery.pageNum = 1
      this.fetchData()
    }
  }
}
</script>
<style scoped>
    .avatar-uploader .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
      border-color: #409EFF;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 300px;
      height: 300px;
      line-height: 178px;
      text-align: center;
    }
    .avatar {
      width: 600px;
      height: 300px;
      display: block;
    }

</style>
